//
//  MainViewController.swift
//  weibo92
//
//  Created by Apple on 15/10/16.
//  Copyright © 2015年 miao. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载完控制器并没有对tabBar进行加载按钮
        
        addControllers()

        setupButton()

    }
     
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //将按钮弄到最前面
        tabBar.bringSubviewToFront(composedBtn)
        
    }
    
    @objc  private func click(){
        print("点我了")

    }
    
    //  MARK: - 懒加载撰写按钮
    //添加撰写按钮
    private lazy var composedBtn: UIButton = {
        //自定义样式按钮
        let button = UIButton()
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        // 让按钮按图片内容大小
        button.sizeToFit()
        
        //MARK : - 添加监听方法
        button.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    

}


//MARK: - 设置界面
extension MainViewController{
    
    ///添加撰写按钮
   private func setupButton(){
        
        tabBar.addSubview(composedBtn)
        
        //自控制器的数量
        let count = childViewControllers.count
        
        
        let w = tabBar.bounds.width / CGFloat(count)
        
        composedBtn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
  
        
    }
    
    ///添加所有控制器
   private func addControllers(){
        

        
        //首页
        addController(HomeTableViewController(), title: "首页", imageName: "tabbar_home" )
        //消息
        addController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        addChildViewController(UIViewController())
        
        //发现
        addController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        //我
        addController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    
    /// Mark: 设置控制器
    private func addController(controller: UIViewController, title: String, imageName: String) {
 
        let vc = controller
        //设置控制器的图标
        vc.tabBarItem.image =  UIImage(named:imageName)

        vc.title = title
        
        let nav =  UINavigationController(rootViewController: vc)
        
        
        
        addChildViewController(nav)
    }
}
